import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
import { useUserStore } from '@/store/modules/user'
import router from '@/router/index'

const loginAgain = useThrottleFn(() => {
  const userStore = useUserStore()
  ElMessageBox.alert('请重新登录', '提示', {
    confirmButtonText: '确定',
    callback: async () => {
      // todo 退出登陆
      userStore.clearCancel()
      const isLogout = await userStore.handleLogout()
      if (isLogout) {
        router.push({ path: '/login', replace: true })
        // location.href = '#/login'
        // window.location.href = '#/login'
      }
    }
  })
}, 1000)

class Request {
  // axios 实例
  instance: AxiosInstance
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = {
    timeout: 60000
    // baseURL: import.meta.env.VITE_BASE_URL
  }

  constructor(config?: AxiosRequestConfig) {
    // 使用axios.create创建axios实例
    this.instance = axios.create(Object.assign(this.baseConfig, config))

    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        const store = useUserStore()
        config.cancelToken = new axios.CancelToken(cancel => {
          // 使用pushCancel，请求进来存入
          store.pushCancel({ cancelToken: cancel })
        })
        if (store.token) {
          config.headers!.Authorization = `Bearer ${store.token}`
        }
        config.headers!.loginType = 'businessPlatform'
        return config
      },
      (err: any) => {
        console.log(err)
        return Promise.reject(err)
      }
    )

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        if (res.data.code == 401) {
          loginAgain()
        }
        return res.data
      },
      (err: any) => {
        if (axios.isCancel(err)) {
          // 使用isCancel 判断是否是主动取消请求
          return new Promise(() => {})
        } else {
          let message = ''
          switch (err.response.status) {
            case 400:
              message = '请求错误(400)'
              break
            case 401:
              message = '未授权，请重新登录(401)'
              loginAgain()
              break
            case 403:
              message = '拒绝访问(403)'
              break
            case 404:
              message = '请求出错(404)'
              break
            case 408:
              message = '请求超时(408)'
              break
            case 500:
              message = err.response.message
                ? err.response.message
                : '服务器错误(500)'
              break
            case 501:
              message = '服务未实现(501)'
              break
            case 502:
              message = '网络错误(502)'
              break
            case 503:
              message = '服务不可用(503)'
              break
            case 504:
              message = '网络超时(504)'
              break
            case 505:
              message = 'HTTP版本不受支持(505)'
              break
            default:
              message = `连接出错(${err.response.status})!`
          }
          ElMessage.error(message)
          return Promise.reject(err.response)
        }
      }
    )
  }

  // 定义请求方法
  public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return this.instance.request(config)
  }
}

// 导出Request类，可以用来自定义传递配置来创建实例
export default Request
